//
//  LzwHomeSingleton.m
//  NewHalfsugar
//
//  Created by 刘志武 on 16/1/14.
//  Copyright © 2016年 刘志武. All rights reserved.
//

#import "LzwHomeSingleton.h"
#import "AFNetworking.h"
@implementation LzwHomeSingleton


/*
 
 post 请求 parameters 填写  字典
 
 get 请求 parameters 填写nil
 
 
 */


+ (void)creatingDataTask:(NSString *)url parameters:(NSDictionary *)parameters Cookie:(NSString *)cookie User_Agent:(NSString *)user_Agent successAFNBlock:(AFNBlock)block {
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    manager.securityPolicy.allowInvalidCertificates = NO;
    
    
    if (parameters) {
        
        NSURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:parameters error:nil];
        
        
        NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
            if (error) {
                NSLog(@"Error: %@", error);
            } else {
                
                block (responseObject);
            }
        }];
        [dataTask resume];
        
        
    }
    else {
        
        NSMutableURLRequest *request =  [[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:url parameters:parameters error:nil];
        
        [request setValue:cookie forHTTPHeaderField:@"Cookie"];
        
        [request setValue:user_Agent forHTTPHeaderField:@"User-Agent"];
        
        NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
            if (error) {
                NSLog(@"Error: %@", error);
            } else {
                
                block (responseObject);
            }
        }];
        [dataTask resume];
        
        
    }
    
    
}

+ (void)getDataFromNetUseGETMethodWithUrl:(NSString *)urlStr andParameters:(NSDictionary *)dicPara successBlock:(AppToolsSuccessBolck)successBlock failBlock:(AppToolsFailBlock)failBlock{
    
    NSString *finalUrlString = [urlStr stringByAppendingString:@"?"];
    for (NSString *key in dicPara) {
        finalUrlString = [finalUrlString stringByAppendingString:[NSString stringWithFormat:@"%@=%@&", key, dicPara[key]]];
    }
    NSLog(@"%d -- %s\n%@", __LINE__, __FUNCTION__, finalUrlString);
    
    NSURL *url = [NSURL URLWithString:finalUrlString];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (data == nil) {
                NSLog(@"%d -- %s\n网络请求失败", __LINE__, __FUNCTION__);
                failBlock(error);
            }else{
                NSLog(@"%d -- %s\nget网络请求数据成功", __LINE__, __FUNCTION__);
                successBlock(data);
            }
            
        });
        
    }];
    
    [task resume];
    
    
}

+ (void)getDataFromNetUsePOSTMethodWithUrl:(NSString *)urlStr andParameters:(NSDictionary *)dicPara successBlock:(AppToolsSuccessBolck)successBlock failBlock:(AppToolsFailBlock)failBlock{
    
    NSString *parameters = @"";
    for (NSString *key in dicPara) {
        parameters = [parameters stringByAppendingString:[NSString stringWithFormat:@"%@=%@&", key, dicPara[key]]];
    }
    NSLog(@"%d -- %s\n%@", __LINE__, __FUNCTION__, parameters);
    
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [parameters dataUsingEncoding:NSUTF8StringEncoding];
    
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (data == nil) {
                NSLog(@"%d -- %s\n网络请求失败", __LINE__, __FUNCTION__);
                failBlock(error);
            }else{
                NSLog(@"%d -- %s\npost网络请求数据成功", __LINE__, __FUNCTION__);
                successBlock(data);
            }
            
        });
        
    }];
    
    [task resume];
    
}

+ (void)getDataFromUrls:(NSString *)urls block:(AppToolsUrlBlock)block{
    NSString *urlStr = urls;
    NSLog(@"%@", urls);
    NSString *urlEncode = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    //创建系统识别的url对象
    NSURL *url = [NSURL URLWithString:urlEncode];
    //创建请求对象,默认是get请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //创建网络请求基本配置对象
    NSURLSessionConfiguration *configur = [NSURLSessionConfiguration defaultSessionConfiguration];
    //创建网络请求对象
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configur];
    //链接服务器，并生成请求任务对象
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (data != nil) {
            //解析data数据
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            //        NSLog(@"result = %@",result);
            block(result);
            
        }
        
    }];
    //执行请求任务
    [task resume];
    
    
    
}

+ (NSString *)createFilePathFromDocumentWithFolders:(NSArray<NSString *> *)folders fileName:(NSString *)fileName{
    NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *finalPath = [NSString stringWithFormat:@"%@", document];
    for (NSString *folder in folders) {
        finalPath = [finalPath stringByAppendingPathComponent:folder];
    }
    
    [[NSFileManager defaultManager] createDirectoryAtPath:finalPath withIntermediateDirectories:YES attributes:nil error:nil];
    
    finalPath = [finalPath stringByAppendingPathComponent:fileName];
    return finalPath;
}

+ (BOOL)saveDataOnLocal:(NSData *)data localPath:(NSString *)path{
    
    return [data writeToFile:path atomically:YES];
}






@end
